"use client"

import type React from "react"

import { useEffect } from "react"
import { Modal, Form, Input, Select, Space, Button, Typography } from "antd"
import type { Host, HostType, Department, Project } from "../types"
import { useHosts } from "../contexts/HostsContext"

const { TextArea } = Input
const { Text } = Typography
const { Option } = Select

interface AddEditHostModalProps {
  visible: boolean
  host: Host | null
  departments: Department[]
  projects: Project[]
  defaultDepartmentId?: string
  defaultProjectId?: string
  onClose: () => void
}

const AddEditHostModal: React.FC<AddEditHostModalProps> = ({
  visible,
  host,
  departments,
  projects,
  defaultDepartmentId,
  defaultProjectId,
  onClose,
}) => {
  const [form] = Form.useForm()
  const { addHost, updateHost } = useHosts()

  useEffect(() => {
    if (visible) {
      if (host) {
        form.setFieldsValue(host)
      } else {
        form.resetFields()
        // Set defaults if provided
        if (defaultDepartmentId) {
          form.setFieldValue("departmentId", defaultDepartmentId)
        }
        if (defaultProjectId) {
          form.setFieldValue("projectId", defaultProjectId)
        }
        form.setFieldValue("type", "frontend")
      }
    }
  }, [visible, host, form, defaultDepartmentId, defaultProjectId])

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()

      if (host) {
        // Update existing host
        updateHost(host.id, values)
      } else {
        // Add new host
        addHost({
          ...values,
          hostContent: `${values.ip} ${values.domain}`,
        })
      }

      form.resetFields()
      onClose()
    } catch (error) {
      console.error("Validation failed:", error)
    }
  }

  const validateIP = (_: any, value: string) => {
    if (!value) {
      return Promise.reject("请输入IP地址")
    }

    const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/
    const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/

    if (!ipv4Regex.test(value) && !ipv6Regex.test(value)) {
      return Promise.reject("请输入有效的IPv4或IPv6地址")
    }

    if (ipv4Regex.test(value)) {
      const parts = value.split(".")
      for (const part of parts) {
        const num = Number.parseInt(part, 10)
        if (num < 0 || num > 255) {
          return Promise.reject("IPv4地址的每个部分必须在0-255之间")
        }
      }
    }

    return Promise.resolve()
  }

  // Filter projects based on selected department
  const filteredProjects = form.getFieldValue("departmentId")
    ? projects.filter((p) => p.departmentId === form.getFieldValue("departmentId"))
    : projects

  return (
    <Modal
      title={host ? "编辑主机" : "添加主机"}
      open={visible}
      onCancel={() => {
        form.resetFields()
        onClose()
      }}
      footer={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" onClick={handleSubmit}>
            确定
          </Button>
        </Space>
      }
      maskClosable={false}
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: "frontend" as HostType,
        }}
        style={{ marginTop: "16px" }}
      >
        <Form.Item name="title" label="名称" rules={[{ required: true, message: "请输入主机名称" }]}>
          <Input placeholder="请输入主机名称" maxLength={50} showCount />
        </Form.Item>

        <Space style={{ width: "100%" }} size="middle">
          <Form.Item
            name="departmentId"
            label="部门"
            rules={[{ required: true, message: "请选择部门" }]}
            style={{ width: "100%" }}
          >
            <Select
              placeholder="请选择部门"
              onChange={() => {
                // Reset project when department changes
                form.setFieldValue("projectId", undefined)
              }}
            >
              {departments.map((dept) => (
                <Option key={dept.id} value={dept.id}>
                  {dept.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="projectId"
            label="项目"
            rules={[{ required: true, message: "请选择项目" }]}
            style={{ width: "100%" }}
          >
            <Select placeholder="请选择项目">
              {filteredProjects.map((project) => (
                <Option key={project.id} value={project.id}>
                  {project.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Space>

        <Space style={{ width: "100%" }} size="middle">
          <Form.Item
            name="ip"
            label="IP地址"
            rules={[{ required: true, validator: validateIP }]}
            style={{ width: "100%" }}
          >
            <Input placeholder="请输入IP地址" />
          </Form.Item>

          <Form.Item
            name="domain"
            label="域名"
            rules={[{ required: true, message: "请输入域名" }]}
            style={{ width: "100%" }}
          >
            <Input placeholder="请输入域名" />
          </Form.Item>
        </Space>

        <Space style={{ width: "100%" }} size="middle">
          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: "请选择主机类型" }]}
            style={{ width: "100%" }}
          >
            <Select>
              <Option value="frontend">前端</Option>
              <Option value="backend">后端</Option>
              <Option value="database">数据库</Option>
              <Option value="cache">缓存</Option>
              <Option value="other">其他</Option>
            </Select>
          </Form.Item>

          <Form.Item name="isComment" label="是否为注释" valuePropName="checked" style={{ width: "100%" }}>
            <Select>
              <Option value={false}>否</Option>
              <Option value={true}>是</Option>
            </Select>
          </Form.Item>
        </Space>

        <Form.Item name="description" label="描述">
          <TextArea placeholder="请输入主机描述信息" autoSize={{ minRows: 2, maxRows: 6 }} maxLength={200} showCount />
        </Form.Item>

        <Form.Item
          name="hostContent"
          label="hosts内容"
          help={<Text type="secondary">格式示例：127.0.0.1 localhost</Text>}
        >
          <TextArea placeholder="请输入hosts配置内容" autoSize={{ minRows: 2, maxRows: 6 }} />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default AddEditHostModal
